package com.ruoyi.auth.controller;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.uuid.IdUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.utils.sign.Base64;
import com.ruoyi.common.core.utils.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.concurrent.TimeUnit;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/auth")
public class CaptchaController {
    @Autowired
    private RedisService redisService;

    @GetMapping("/captchaImage")
    public R<?> getCode(HttpServletResponse response) {
        // 生成验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        // 保存验证码到redis
        redisService.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

        // 生成图片
        BufferedImage image = VerifyCodeUtils.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", outputStream);
        } catch (Exception e) {
            return R.fail("生成验证码失败");
        }
        String img = Base64.encode(outputStream.toByteArray());

        Map<String, String> data = new HashMap<>();
        data.put("uuid", uuid);
        data.put("img", "data:image/jpg;base64," + img);
        return R.ok(data);
    }
}